(function(){

    var ClientFunctions = {};
    var ClientCallbacks = {};
    var uniqueId = 1;
    
    function getUniqueId() {
        return ++uniqueId + "_" + new Date().getTime();
    }

    function _Register(funcName, func) {
        ClientFunctions[funcName] = func;
    }

    function _callNative(params, callback, methodName) {
        if (methodName) {
            var callbackId = getUniqueId();
            ClientCallbacks[callbackId] = callback;
            try {
                NativeComm.call(
                    JSON.stringify(
                        {
                            method: methodName,
                            callbackId: callbackId,
                            params: params
                        }
                    )
                );
            } catch (e) {
                callback({
                    status: 0,
                    msg: 'Native invocation exception' + e
                });
            }
        } else {
            try{
                NativeComm.call(JSON.stringify(params));
            } catch (e) {
                throw "The native callback of javascript invoke failed.";
            }
        }
    }

    // 原生响应处理器
    function _NotifyFromNative(message) {
        try {
            if(message.id) {
                // 响应回调函数存在
                var handler = ClientCallbacks[message.id];
                if (handler) {
                    handler(message);
                    delete ClientCallbacks[message.id];
                }
            } else if (message.method) {
                var handler = ClientFunctions[message.method];
                if (handler) {
                    handler(message);
                } else {
                    throw "The javascript method of native invoke don't exists."
                }
            } else {
                throw "The javascript callback of native invoke don't exists."
            }
        } catch(e) {
            throw e;
        }
    }

    var _TVBridge = {
        call: _callNative,
        notifyFromNative: _NotifyFromNative,
        register: _Register
    };
    window.TVBridge = _TVBridge;
})();